package com.yeyaomai.dksns.flowis.util;

import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.core.JdbcTemplate;

/**
 * 
 * @author dingtao@yeyaomai.com
 * 
 */
public class LoadSchemaTool implements InitializingBean {

	private Logger logger = LoggerFactory.getLogger(this.getClass());

	private Resource sqlSchema;

	private JdbcTemplate jdbcTemplate;

	public void loadSchema() {

		try {
			jdbcTemplate.execute(getSqlScript(sqlSchema));
		} catch (Exception e) {
			logger.error("table construct load fail ingore" + e.getMessage());

		}
	}

	private String getSqlScript(Resource scriptSqlFile) {

		char[] buffer = new char[1024 * 4];

		int length;

		try {
			Reader reader = new InputStreamReader(
					scriptSqlFile.getInputStream(), "utf-8");

			StringWriter writer = new StringWriter();

			while ((length = reader.read(buffer)) >= 0) {
				writer.write(buffer, 0, length);
			}
			return writer.toString();

		} catch (Exception e) {
			throw new RuntimeException(e);
		}

	}

	@Override
	public void afterPropertiesSet() throws Exception {

		loadSchema();
	}

	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}

	public void setSqlSchema(Resource sqlSchema) {
		this.sqlSchema = sqlSchema;
	}
}
